<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <textarea name="textarea" id="textarea" cols="30" rows="10"></textarea>
    <button onclick="translateToVoice()">一键转换</button>
    <button onclick="changeVoice()">切换声音</button>
    <button onclick="start()">播放</button>
    <button onclick="stop()">暂停</button>
    <div id="error"></div>
    <script>

        if (!window.SpeechSynthesisUtterance) {
            alert("不支持语音，请使用其他浏览器！")
        }
        class Speaker {
            speaker;
            constructor(text = '', volume = 1, lang = 'zh-CN') {
                this.speaker = new SpeechSynthesisUtterance()
                this.speaker.text = text
                this.speaker.volume = volume
                this.speaker.lang = lang
            }
            play() {
                // google chrome播放语音可能会卡住，所以无声音
                // 解决方法：在播放语音之前先 调用一下cancel方法：
                this.stop()
                speechSynthesis.speak(this.speaker)
            }
            stop() {
                speechSynthesis.cancel()
            }
            setText(text) {
                this.speaker.text = text
            }
            setVolume(volume = 1) {
                if (volume < 0 || volume > 1) {
                    return
                }
                this.speaker.volume = volume
            }
            setVoice(voice) {
                this.speaker.voice = voice
            }
        }
        const textarea = document.querySelector('#textarea')
        let speak = new Speaker()

        let voiceList = []
        let index = 0
        speechSynthesis.addEventListener('voicechanged', () => {
            voiceList = speechSynthesis.getVoices()

        })
        const start = () => {
            speak.play()
        }
        function translateToVoice() {
            console.log(textarea.value)
            speak.setText(textarea.value)
        }
        const changeVoice = () => {
            index++
            speak.setVoice(voiceList[index])
        }
        const stop = () => {
            speak.stop()
        }
        window.addEventListener('error', (e) => {
            console.log(e.target)
            document.getElementById('error').innerHTML = e.target
        })
    </script>
</body>

</html>